# Packages ----------------------------------------------------------------

if(!require(pacman)){install.packages("pacman")}
pacman::p_load(tidyverse, scales, broom, MetBrewer)

# Data --------------------------------------------------------------------

data <- read_dta("data/adopted_methods_public.dta")
data <- data %>% 
  # filter(data, view != "MiM") %>% 
  # mutate(
  #   view = ifelse(view == "SBS", "IDM", "SDM")
  # ) %>% 
  # Fix client with wrong ndm
  mutate(
    ndm = ifelse(client_id_nopii == 634, 1, ndm)
  ) %>% 
  mutate(
    view = case_when(
      view == "SBS" ~ "IDM", 
      view == "SEQ" ~ "SDM",
      view == "MiM" ~ "MiM"
    ),
    view = fct_relevel(view, "MiM", "IDM", "SDM")
  )

# NDM ---------------------------------------------------------------------

means <- data %>% 
  filter(view != "MiM") %>% 
  group_by(view) %>% 
  summarize(
    mean = mean(ndm, na.rm = TRUE),
    sd   = sd(ndm, na.rm = TRUE)
  ) %>% 
  mutate(
    glue = glue::glue("{view}={round(mean,3)} ({round(sd,2)})")
  ) %>% 
  select(glue) %>% 
  ungroup() %>% 
  summarize(
    text = paste(glue, collapse = "\n")
  )

value <- data %>% 
  filter(view != "MiM") %>% 
  do(tidy(t.test(ndm ~ view, data = .))) %>% 
  select(p.value) %>% 
  mutate(
    value = ifelse(p.value < 0.001, "p value < 0.001", NA_character_)
  ) %>% 
  select(value)

text <- paste0("Mean (SD) by counseling regime\n", means, "\nSDM vs. IDM: ", value)

data %>%
  count(ndm, view) %>% 
  group_by(view) %>% 
  mutate(
    pct = n / sum(n)
  ) %>% 
  ggplot(
    aes(
      x = ndm,
      y = pct, 
      fill = view
    )
  ) +
  geom_col(
    color = "black", 
    position = position_dodge2(width = 0.9, preserve = "single")
  ) +
  geom_text(
    aes(
      label = paste0("N=",n, "\n",round(pct * 100,1), "%")
    ),
    position = position_dodge2(width = .9, preserve = "single"),
    vjust = -0.2,
    size = 2.7
  ) +
  annotate(
    "text",
    x = 5.5, y = 0.9,
    label = text,
    hjust = 1,
    size = 3
  )+
  labs(
    x = "Number of methods",
    y = "",
    fill = "",
    title = "Number of methods discussed in detail"
  ) + 
  scale_x_continuous(breaks = seq(0,5,1)) +
  scale_y_continuous(labels = percent, limits = c(0,1)) +
  scale_fill_manual(values = met.brewer("Kandinsky", 3)) +
  theme_bw() +
  theme(
    panel.grid.minor = element_blank(), 
    panel.grid.major = element_blank(),
    legend.position = "bottom"
  )

ggsave("output/figures/Fig3-ndm_mim_r.png", dpi = 320, scale = 0.9,height = 14, width = 20, units = "cm")
